package com.example.demo.exception;

import com.example.demo.response.CustomRspBody;
import com.example.demo.response.RspCodeInfoEnum;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

//统一全局异常处理
@RestControllerAdvice
public class GlobalExceptionHandle {
    private static final Log logger = LogFactory.getLog("GlobalExceptionHandle");

    /** @description 自定义异常 */
    @ExceptionHandler(TheCustomException.class)
    public CustomRspBody customException(TheCustomException e){
        RspCodeInfoEnum codeInfoEnum = e.getRspCodeInfoEnum();
        logger.error("\n自定义异常，错误信息：" + codeInfoEnum.toString() + ", 异常信息：",e);
        return new CustomRspBody(codeInfoEnum,null);
    }

    /**@descrition 空指针异常 */
    @ExceptionHandler(NullPointerException.class)
    public CustomRspBody NullException(NullPointerException e){
        logger.error("\n空指针异常,错误信息为：",e);
        return new CustomRspBody(RspCodeInfoEnum.Null_Pointer,null);
    }

    /** 其它异常 */
    @ExceptionHandler(Exception.class)
    public CustomRspBody exceptionHandle(Exception e){
        logger.error("\n其它异常(非空指针和自定义异常)，信息为：",e);
        return new CustomRspBody(-2000, e.getMessage(),null);
    }
}
